package com.servlet;

import com.dao.SalasDao;
import com.dao.impl.SalasDaoImpl;
import com.entry.Sales;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.util.PageModel;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(urlPatterns = "/PSales/salas.do")
public class SalasServlet extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        HttpSession session = req.getSession();
        JsonParser jParser = new JsonParser();
        SalasDao salasDao = new SalasDaoImpl();
        int pageSize = req.getParameter("pageSize") == null ? 5 : Integer.parseInt(req.getParameter("pageSize").toString());
        int pageNo = req.getParameter("pageNo") == null ? 1 : Integer.parseInt(req.getParameter("pageNo").toString());
        if(req.getParameter("pageNo") == null || req.getParameter("pageSize") == null){
            session.removeAttribute("c2");
        }
        JsonObject jt = null;
        if(session.getAttribute("c2") == null){
            jt = (JsonObject) jParser.parse(req.getParameter("c2"));
        }else{
            jt = (JsonObject) jParser.parse(String.valueOf(session.getAttribute("c2")));
        }
        String gid = jt.get("gid").getAsString();
        String sname = jt.get("sname").getAsString();
        try{
            float stapirce = "".equals(jt.get("stapirce").getAsString())?0:Float.valueOf(jt.get("stapirce").getAsString());
            float endpirce = "".equals(jt.get("endpirce").getAsString())?0:Float.valueOf(jt.get("endpirce").getAsString());
            JsonObject language1=new JsonObject();
            language1.addProperty("gid", gid);
            language1.addProperty("sname", sname);
            language1.addProperty("stapirce", String.valueOf(stapirce));
            language1.addProperty("endpirce", String.valueOf(endpirce));
            PageModel<Sales> pm  = salasDao.find(pageSize,pageNo,gid,sname,stapirce,endpirce);
            pm.setPageNav(req.getRequestURI()+"?c2=" + language1);
            session.setAttribute("c2",language1);
            session.setAttribute("sa",pm);
            resp.sendRedirect("./salas.jsp");
        }catch (NumberFormatException e){
            resp.sendRedirect("./salas.jsp");
        }

    }
}
